'''
Created on Mar 23, 2013

@author: Petko
'''
from django.views.generic.base import View
from sent.utils import createValidToken, CommonResult, ErrorIds, AccessToken
from sent.utils.result_printer import getPrinter
from sent.model.OpinionDBManager import OpinionDBManager
from sent.model.entities.opinion import Opinion, OpinionEvaluations, OpinionState, PendingUpdateState
from sententialyzer.settings import DEBUG
import time
from sent.utils.commit_scheduler import g_commit_scheduler

class DeleteOpinion(View):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        pass
    
    def post(self, *args, **kwargs):
        accessTokenStr = self.request.POST.get('access_token', None)
        opinionId = self.request.POST.get('opinion_id', None)
        
        commit_delay=0
        if DEBUG:
            commit_delay = float(self.request.POST.get('commit_delay', 0))
            
        common_res = CommonResult()
        
        if accessTokenStr and opinionId:
            
            accessToken, error = createValidToken(accessTokenStr)
            if accessToken:
                dbman = OpinionDBManager(False)
                try:
                    opinion = dbman.get_opinion_by_id_str(opinionId, 'update')
                    if opinion:
                        assert isinstance(opinion, Opinion)
                        assert isinstance(accessToken, AccessToken)
                        
                        if opinion.getCreatorUUID() == accessToken.getOwnerUUID() or \
                            accessToken.containsScope(str(opinion.getBaseUUID()) + ':d'):
                        
                            base_op_id = opinion.base_op_id
                            pending_ud = dbman.lock_base_op_ro(base_op_id)
                            if pending_ud:
                                dbman.expunge(pending_ud)
                                
                            if opinion.op_state == OpinionState.INSERTED or opinion.nested_set_left == opinion.nested_set_right - 1:
                                #a "leaf" opinion
                                dbman.delete_opinion(opinion, True)
                                
                                common_res.result = "Deleted leaf"
                                
                            else:
                                #delete only the text
                                dbman.delete_opinion(opinion, False)
                                
                                if opinion.evaluation != OpinionEvaluations.NEUTRAL:
                                    #and neutralize
                                    
                                    assert opinion.op_state != OpinionState.INSERTED and opinion.op_state != OpinionState.WAITING_DELETE
                                    
                                    if opinion.op_state == OpinionState.NORMAL:
                                        opinion.prev_eval = opinion.evaluation
                                    
                                    opinion.evaluation = OpinionEvaluations.NEUTRAL
                                
                                    opinion.op_state = OpinionState.WAITING_UPDATE
                                
                                    dbman.update_opinion(opinion)
                                    
                                common_res.result = "Deleted text only"
                            
                            if commit_delay>0:
                                time.sleep(commit_delay)
                                
                            dbman.commitSession()
                            
                            if not pending_ud or pending_ud.state == PendingUpdateState.IDLE:
                                dbman.set_base_op_for_update(base_op_id)
                                dbman.commitSession()
                            
                            g_commit_scheduler.schedule_commit()
                            
                            common_res.errorId = ErrorIds.SUCCESS
                        else:
                            common_res.errorId = ErrorIds.UNAUTHORIZED
                            common_res.result = "You must be either owner, or have the 'd' permission for base opinion %s" % str(opinion.getBaseUUID())
                    else:
                        dbman.rollbackSession()
                        common_res.errorId = ErrorIds.NOT_FOUND
                        common_res.result = "Opinion %s not found" % opinionId
                except:
                    dbman.rollbackSession()
                    raise
            else:
                common_res.errorId = ErrorIds.UNAUTHORIZED
                common_res.result = error
        else:
            common_res.errorId = ErrorIds.BADREQUEST
            common_res.result = "Missing parameter"
            
        return getPrinter().printResult(common_res)
    
    